<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialog"
            >添加分类</el-button
          >
        </el-col>
      </el-row>

      <!-- 表格 -->
      <tree-table
        class="treeTable"
        :data="cateList"
        :columns="columns"
        show-index
        index-text="#"
        border
        stripe
        :expand-type="false"
        :selection-type="false"
      >
        <!-- 是否有效模板 -->
        <template slot="isOk" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>
        <!-- 排序模板 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag
            type="success"
            size="mini"
            v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag type="warning" size="mini" v-else>三级</el-tag>
        </template>
        <!-- 操作模板 -->
        <template slot="opt">
          <el-button type="primary" icon="el-icon-edit" size="mini"
            >编辑</el-button
          >
          <el-button type="danger" icon="el-icon-delete" size="mini"
            >删除</el-button
          >
        </template>
      </tree-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCatedialogVisible"
      width="50%"
      @close="addCatedialogClose"
    >
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="addCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类：">
          <!-- 级联选择器 -->
          <el-cascader
            ref="cascaderRef"
            @click.native="cascaderClick"
            :popper-class="'cascader' + cascaderId"
            v-model="selectedKeys"
            :options="parentCateList"
            :props="cascaderProps"
            @change="parentCateListChanged"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCatedialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCateInfo"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 商品分类列表
      cateList: [],
      // 查询条件
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 总条数
      total: 0,
      columns: [
        {
          // 列名称
          label: '分类名称',
          // 列绑定属性
          prop: 'cat_name'
        },
        {
          // 列名称
          label: '是否有效',
          // 表示当前模板列为自定义模板列
          type: 'template',
          // 指定自定义模板
          template: 'isOk'
        },
        {
          // 列名称
          label: '排序',
          // 表示当前模板列为自定义模板列
          type: 'template',
          // 指定自定义模板
          template: 'order'
        },
        {
          // 列名称
          label: '操作',
          // 表示当前模板列为自定义模板列
          type: 'template',
          // 指定自定义模板
          template: 'opt'
        }
      ],
      // 是否显示添加分类对话框
      addCatedialogVisible: false,
      // 添加分类表单对象
      addCateForm: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0
      },
      // 添加分类规则对象
      addCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      // 父级分类列表
      parentCateList: [],
      // 选择的ID
      selectedKeys: [],
      cascaderProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: true
      },
      // 级联选择器ID
      cascaderId: 'cate'
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取商品分类列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类列表失败！')
      }

      console.log(res.data)

      this.cateList = res.data.result

      this.total = res.data.total
    },
    // 当前pagesize改变事件
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getCateList()
    },
    // pagenum改变事件
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getCateList()
    },
    // 展示对话框
    showAddCateDialog () {
      this.getParentCateList()
      this.addCatedialogVisible = true
    },
    // 获取父级选择分类列表
    async getParentCateList () {
      const { data: res } = await this.$http.get('categories', {
        params: {
          type: 2
        }
      })

      if (res.meta.status !== 200) {
        return this.$message.error('获取父级分类列表失败！')
      }

      this.parentCateList = res.data

      console.log(this.parentCateList)
    },
    // 级联选择器改变事件
    parentCateListChanged () {
      if (this.selectedKeys.length > 0) {
        this.addCateForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
      } else {
        this.addCateForm.cat_pid = 0
      }
      this.addCateForm.cat_level = this.selectedKeys.length
    },
    // 对话框关闭事件
    addCatedialogClose () {
      // 重置清空表单
      this.$refs.addCateFormRef.resetFields()

      this.selectedKeys = []
      this.addCateForm.cat_level = 0
      this.addCateForm.cat_pid = 0
    },
    // 添加分类信息
    addCateInfo () {
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.post('categories', this.addCateForm)
        if (res.meta.status !== 201) return this.$message.error('添加分类信息失败！')
        this.$message.success('添加分类信息成功！')
        this.getCateList()

        this.addCatedialogVisible = false
      })
    },
    // 元素选中
    elCascaderOnlick () {
      const that = this
      setTimeout(function () {
        document.querySelectorAll('.el-cascader-node__label').forEach(el => {
          el.onclick = function () {
            this.previousElementSibling.click()
            that.$refs.cascaderRef.dropDownVisible = false
          }
        })
        document
          .querySelectorAll('.el-cascader-panel .el-radio')
          .forEach(el => {
            el.onclick = function () {
              that.$refs.cascaderRef.dropDownVisible = false
            }
          })
      }, 100)
    },
    cascaderClick (event) {
      const that = this
      this.$nextTick(() => {
        const d = document.getElementsByClassName('cascader' + this.cascaderId)
        if (d[0] && !d[0].onclick) {
          d[0].onclick = function (e) {
            console.log(e)
            if (e.target.className === 'el-cascader-node__label') {
              e.target.previousElementSibling.click()
              that.$refs.cascaderRef.dropDownVisible = false
            }
          }
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.treeTable {
  margin-top: 15px;
  margin-bottom: 10px;
}
.el-cascader {
  width: 100%;
}

</style>
